package com.yoo.ons.function.account

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.util.Log
import androidx.core.content.ContextCompat
import com.google.android.gms.auth.api.signin.GoogleSignIn
import com.google.android.gms.auth.api.signin.GoogleSignInAccount
import com.google.android.gms.common.api.ApiException
import com.google.android.gms.tasks.Task
import com.yoo.chat.kit.utils.StatusBarUtil
import com.yoo.module_base.dialog.CustomPopup
import com.yoo.module_base.utils.SaveDeviceUtil
import com.yoo.module_base.utils.setOnClickCallback
import com.yoo.ons.R
import com.yoo.ons.ToastUtil
import com.yoo.ons.base.BaseVMActivity
import com.yoo.ons.base.HttpRequestListener
import com.yoo.ons.databinding.ActivityMyAccountBinding
import com.yoo.ons.function.MainActivity
import com.yoo.ons.function.account.viewmodel.MyAccountViewModel
import com.yoo.ons.function.login.PhoneLoginActivity
import com.yoo.ons.function.register.RegisterActivity
import com.yoo.ons.model.LoginResultModel
import com.yoo.ons.model.UserAccountModel
import com.yoo.ons.util.UserUtil
import io.reactivex.annotations.Nullable

class MyAccountActivity:BaseVMActivity<ActivityMyAccountBinding,MyAccountViewModel>(ActivityMyAccountBinding::inflate,
    MyAccountViewModel::class.java
) {
    private var phoneBind= false //手机号绑定状态
    private var emailBind= false //邮箱绑定状态
    private val GOOGLE_SIGN_IN:Int = 1111

    override fun initView() {
        super.initView()
        binding.titleBar.setTitleText(getString(com.yoo.module_res.R.string.my_account))
        binding.titleBar.setTitleBarPadding(StatusBarUtil.getStatusBarHeight(this))
        binding.titleBar.setBackListener {
            finish()
        }
    }
    override fun initData() {
        mViewModel?.getUserAccount(object :HttpRequestListener<UserAccountModel>(){
            override fun addRequestParams(params: HashMap<String, Any>) {
                
            }

            override fun success(t: UserAccountModel?) {
               t?.apply {
                   binding.imgAccountLogo.setImageResource(if (t.loginType==1)com.yoo.module_res.R.mipmap.img_phone else com.yoo.module_res.R.mipmap.img_google)
                   binding.txtAccountWay.text = getText(if (t.loginType==1)com.yoo.module_res.R.string.phone_number else com.yoo.module_res.R.string.google)

                   binding.txtGoogleBindStatus.setTextColor(ContextCompat.getColor(this@MyAccountActivity,if (t.googleBind)  com.yoo.module_res.R.color.color_FF3EAB else  com.yoo.module_res.R.color.color_9C9FA6))
                   binding.txtGoogleBindStatus.text = if (t.googleBind) t.googleName else getString(com.yoo.module_res.R.string.connect_now)

                   binding.txtPhoneNumberBindStatus.setTextColor(ContextCompat.getColor(this@MyAccountActivity, if (t.mobileBind) com.yoo.module_res.R.color.color_FF3EAB else com.yoo.module_res.R.color.color_9C9FA6))
                   binding.txtPhoneNumberBindStatus.text = if (t.mobileBind) t.mobile else getString(com.yoo.module_res.R.string.connect_now)
                   emailBind=googleBind
                   phoneBind=mobileBind
               }
            }

        })
    }

    override fun initListener() {
        super.initListener()
        //账号退出
        binding.txtSettingLogOut.setOnClickCallback {
            CustomPopup(this)
                .setLayoutId(R.layout.popup_log_out_account)
                .setOnClickListener(R.id.txt_cancel) { dialog, _ ->
                    run {
                        dialog.dismiss()
                    }
                }
                .setOnClickListener(R.id.txt_log_out) { dialog, _ ->
                    dialog.dismiss()
                    UserUtil.out(this)
                }.show()
        }
        //账号删除
        binding.txtSettingDeleteAccount.setOnClickCallback {
            CustomPopup(this)
                .setLayoutId(R.layout.popup_delete_account)
                .setOnClickListener(R.id.tvCancel) { dialog, view ->
                    run {
                        dialog.dismiss()
                    }
                }
                .setOnClickListener(R.id.tvDelete) { dialog, view ->
                    dialog.dismiss()
                    mViewModel?.getUserDelete(object : HttpRequestListener<String>() {
                        override fun addRequestParams(params: HashMap<String, Any>) {
                        }

                        override fun success(t: String?) {
                            UserUtil.deleteAccount(this@MyAccountActivity)
                        }

                    })
                }.show()
        }

        binding.googleContainer.setOnClickCallback {
            if (phoneBind && emailBind) {
                CustomPopup(this)
                    .setLayoutId(R.layout.popup_change_account)
                    .setTitle(R.id.popup_title,getString(com.yoo.module_res.R.string.unbind_google))
                    .setContent(R.id.popup_content,getString(com.yoo.module_res.R.string.unbind_google_content))
                    .setConfirmText(R.id.txt_confirm,getString(com.yoo.module_res.R.string.unbind))
                    .setCancelText(R.id.txt_cancel,getString(com.yoo.module_res.R.string.cancel))
                    .setOnClickListener(R.id.txt_cancel) { dialog, view ->
                        run {
                            dialog.dismiss()
                        }
                    }
                    .setOnClickListener(R.id.txt_confirm) { dialog, view ->

                        mViewModel?.getRemoveAccount(object :HttpRequestListener<LoginResultModel>(){
                            override fun addRequestParams(params: HashMap<String, Any>) {
                                params["accountType"]=2
                            }

                            override fun success(t: LoginResultModel?) {
                                ToastUtil.showToast(getString(com.yoo.module_res.R.string.unbind))
                                initData()
                                UserUtil.googleLogin(this@MyAccountActivity).signOut()
                            }

                            override fun error(throwable: Throwable) {
                                super.error(throwable)
                                ToastUtil.showToast(throwable.message)
                            }

                            override fun endRequest() {
                                super.endRequest()
                                dialog.dismiss()
                            }

                        })
                    }.show()
            } else {
                showProgressDialog(this)
                val signInIntent = UserUtil.googleLogin(this).signInIntent
                startActivityForResult(signInIntent, GOOGLE_SIGN_IN)
            }
        }

        binding.phoneNumberContainer.setOnClickCallback {
            if (phoneBind) {
                CustomPopup(this)
                    .setLayoutId(R.layout.popup_change_account)
                    .setTitle(R.id.popup_title,getString(com.yoo.module_res.R.string.change_phone_number))
                    .setContent(R.id.popup_content,getString(com.yoo.module_res.R.string.change_phone_number_content))
                    .setConfirmText(R.id.txt_confirm,getString(com.yoo.module_res.R.string.change))
                    .setCancelText(R.id.txt_cancel,getString(com.yoo.module_res.R.string.cancel))
                    .setOnClickListener(R.id.txt_cancel) { dialog, view ->
                        run {
                            dialog.dismiss()
                        }
                    }
                    .setOnClickListener(R.id.txt_confirm) { dialog, view ->
                        dialog.dismiss()
                        PhoneLoginActivity.startForResult(this,"account")
                    }.show()
            } else {
                PhoneLoginActivity.startForResult(this,"account")
            }
        }

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode==1001 && resultCode == 1002){
            binding.txtPhoneNumberBindStatus.text= data?.getStringExtra("mobile")
        }else if (requestCode == GOOGLE_SIGN_IN && resultCode != 0) {//谷歌登录信息返回
            hideProgressDialog()
            val task: Task<GoogleSignInAccount> = GoogleSignIn.getSignedInAccountFromIntent(data)
            handleSignInResult(task)
        } else if (requestCode == GOOGLE_SIGN_IN) {
            hideProgressDialog()
            assert(data != null)
            ToastUtil.showToast(data.toString())
        }
    }

    /**
     * Google登录成功返回数据
     * @param completedTask
     */
    private fun handleSignInResult(completedTask: Task<GoogleSignInAccount>) {
        try {
            val account = completedTask.getResult(ApiException::class.java)
            mViewModel?.getAccountBind(object : HttpRequestListener<LoginResultModel>() {
                override fun addRequestParams(params: HashMap<String, Any>) {
                    account.account?.name?.let { params["account"]=it }
                    account.email?.let { params["email"]= it }
                    params["accountType"]="2"
                    account.displayName?.let { params["userName"]= it }

                }

                override fun success(t: LoginResultModel?) {
                    initData()
                }

                override fun error(throwable: Throwable) {
                    super.error(throwable)
                    ToastUtil.showToast(throwable.message)
                }

            })
        } catch (e: ApiException) {
        }
    }


    companion object{
        fun start(context: Context){
            val intent = Intent(context, MyAccountActivity::class.java)
            context.startActivity(intent)
        }
    }

}